<template>
    <Layout>
        <Form :label-width="120" ref="formInline" :model="searchTable">
            <Row class="query-form">
                <Col span="8">
                    <FormItem label="题目类型：">
                        <Select v-model='searchTable.questionType' style="width: 100%;">
                            <Option v-for="item in questionTypeArr" :value="item.value" :key="item.value">{{item.lable }}
                            </Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="8" >
                    <FormItem label="题目标题：" prop="teamName">
                        <Input v-model="searchTable.questionInfo" />
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="search">查询</Button>
                </Col>
            </Row>
        </Form>
        <Row class="query-form">
            <Col span="24">
                <Button size="large" class="ivu-btn-add" icon="md-add" @click="exercise('order')">顺序练习</Button>
                <Button size="large" class="ivu-btn-add" icon="md-add" @click="exercise('random')">随机练习</Button>
            </Col>
        </Row>
        <Table ref='table' :loading="listLoading" border :columns="baseColumns"
               :data="tableData" no-data-text="没有查询到相关数据!"  :height="tableHeight" highlight-row stripe size="small">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                      @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal v-model="showEdit" title="错题练习" width="900" :mask-closable="false">
            <div class="dialog_body" style="overflow-y: scroll;height: calc(100vh - 280px);;">
                <Card dis-hover style="margin: 0 15px">
                    <div slot="header" style="color:blue;">
                        <p slot="title">
                            错题练习  (共{{ questionData.length }}道)
                        </p>
                    </div>
                    <Row>
                        <Card v-for="(item, index) in questionData" :key="index"
                              :style="{backgroundImage: 'url(' + item.imgPath + ')', backgroundRepeat: 'no-repeat', backgroundSize: '13% 100%', backgroundPosition: 'right top'}">
                            <div style="width:100%">
                                <p class="problem_item">{{ index+1 }}、<span style="font-weight: bolder;">({{ item.questionType === 'radio' ? '单选' : item.questionType === 'checkbox' ? '多选' : '判断' }})</span>  {{ item.questionInfo }}</p>
                                <RadioGroup v-if="item.questionType === 'radio'" v-model="item.checked" :disabled="saveStatus">
                                    <p v-for="(aw, index2) in item.questionDetailList" :key="index2" class="checkbox_item" :label="index2">
                                        <Radio :label="aw.questionDetailId">
                                            <span>{{ aw.answerOption }}</span>
                                        </Radio>
                                    </p>
                                </RadioGroup>
                                <CheckboxGroup v-if="item.questionType === 'checkbox'" v-model="item.checkedbox" :disabled="saveStatus">
                                    <p v-for="(aw, index3) in item.questionDetailList" :key="index3" class="checkbox_item" :label="index3">
                                        <Checkbox :label="aw.questionDetailId">
                                            <span>{{ aw.answerOption }}</span>
                                        </Checkbox>
                                    </p>
                                </CheckboxGroup>
                                <RadioGroup v-if="item.questionType === 'judge'" v-model="item.checked" :disabled="saveStatus">
                                    <p v-for="(aw, index2) in item.questionDetailList" :key="index2" class="checkbox_item" :label="index2">
                                        <Radio :label="aw.questionDetailId">
                                            <span>{{ aw.answerOption }}</span>
                                        </Radio>
                                    </p>
                                </RadioGroup>
                                <ShowAnswer v-if="saveStatus" :answer="item" />
                                <el-divider v-if="index < questionData.length-1" v-show="index <questionData.length-1" />
                            </div>
                        </Card>
                    </Row>
                </Card>
            </div>
            <div slot="footer">
                <Button v-if="!saveStatus" class='ivu-btn-save' :loading="submitBtn" @click="submit">完成</Button>
                <Button v-if="!saveStatus" class='ivu-btn-cancel' @click="showEdit=false,questionBase=[]">取消</Button>
                <Button v-if="saveStatus" class='ivu-btn-cancel' @click="saveClose">取消</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api'
    import qs from "qs";
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';
    import {formatDate} from '@/tools/index'
    import ShowAnswer from '../answer/showAnswer'
    import timg from '../answer/timg.png'
    import timg2 from '../answer/timg2.jpg'

    export default {
        components: {ShowAnswer},
        data(){
            return{
                img: timg,
                img2: timg2,
                questionTypeArr: [{ lable: '单选', value: 'radio' }, { lable: '多选', value: 'checkbox' }, { lable: '判断', value: 'judge' }],
                searchTable: {
                    questionType: '',
                    questionInfo: ''
                },
                pagedata: {
                    pageNumber: 1,
                    pageSize: 10,
                    total: 0
                },
                pageSizeArray: [10, 20, 50],
                tableData: [],
                listLoading: false,
                formLoading: false,
                submitBtn: false,
                questionData: [],
                showEdit: false,
                checked1: [],
                saveStatus: false,
                baseColumns: [
                    {type: 'index', title: '编号', width: 80, align: 'center', fixed: 'left'},
                    {title: '题目类型', minWidth:100,align: 'center', key: 'questionType',render:(h, params)=> {
                            return h('span', params.row.questionType === 'radio' ? '单选题' : params.row.questionType === 'checkbox' ? '多选题' : '判断题')}},
                    {title: '题目标题', minWidth:180,align: 'center', key: 'questionInfo',tooltip:true},
                    {title: '答题次数',minWidth:180, align: 'center', key: 'answerNum'},
                    {title: '错误次数',minWidth:100, align: 'center', key: 'errorNum'},
                    {title: '正确率',minWidth:90, align: 'center', key: 'correctRate',render:(h, params)=> {
                            return h('span', params.row.correctRate+'%' )}},
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 120,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.row.errorQuestionId);
                                        }
                                    }
                                }, '移出错题库'),
                            ]);
                        }
                    }
                ],
                tableHeight:300,
                currentUser: JSON.parse(sessionStorage('userId').get('userId')),

            }
        },
        mounted(){
            this.companyId=sessionStorage('userId').getObject('userId').companyId
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop-145;
            this.query();
        },
        watch: {
        },
        methods:{
            saveClose() {
                this.showEdit = false
                this.questionBase = []
                this.saveStatus = false
                this.search()
            },
            // 判断多选是否相等
            checkJudge(arr1, arr2) {
                let flag = true
                if (arr1.length !== arr2.length) {
                    flag = false
                } else {
                    arr1.forEach(item => {
                        if (arr2.indexOf(item) === -1) {
                            flag = false
                        }
                    })
                }
                return flag
            },
            // 练习 order：顺序练习；random：随机练习
            exercise(type) {
                this.listLoading = true
                this.$http.get(Api.paper+'/practiceErrorQuestion/'+type).then(res => {
                    if (res.data.status === 200) {
                        if (res.data.data.length > 0) {
                            res.data.data.forEach(item => {
                                item.checkedbox = []
                            })
                            this.questionData = res.data.data
                            this.showEdit = true
                            this.listLoading = false
                        }
                    } else {
                        this.listLoading = false
                        this.$Message.error(res.data.msg)
                    }
                }).catch(item => {
                    this.listLoading = false
                })
            },
            submit(type) {
                this.formLoading = true
                this.submitBtn = true
                this.questionBase = []
                this.questionData.forEach(item => {
                    if (item.questionType === 'radio' || item.questionType === 'judge') {
                        const ckeck = item.checked !== '' && item.checked !== undefined ? item.checked : ''
                        const radio = {'questionId': item.questionId}
                        item['ifJudge'] = item.questionType === 'judge'
                        const questionDetailList = item['questionDetailList']
                        for (let j = 0; j < questionDetailList.length; j++) {
                            const questionDetail = questionDetailList[j]
                            if (questionDetail.correctOption === '1') {
                                radio['answer'] = questionDetail.questionDetailId
                            }
                        }
                        // 试题结果
                        let questionResult = '1'
                        if (radio.answer === ckeck) {
                            questionResult = '0'
                            // item['imgPath'] = this.img2
                        } else {
                            questionResult = '1'
                            // item['imgPath'] = this.img
                        }
                        item['questionResult'] = questionResult
                        radio['questionResult'] = questionResult
                        this.questionBase.push(radio)
                    } else if (item.questionType === 'checkbox') {
                        item.checked = item.checkedbox
                        const checkbox = { 'questionId': item.questionId }
                        const answerArray = []
                        const questionDetailList = item['questionDetailList']
                        for (let j = 0; j < questionDetailList.length; j++) {
                            const questionDetail = questionDetailList[j]
                            if (questionDetail.correctOption === '1') {
                                answerArray.push(questionDetail.questionDetailId)
                            }
                        }
                        checkbox['answer'] = answerArray
                        let questionResult = '1'
                        // 多选顺序
                        const flag = this.checkJudge(answerArray, item.checkedbox)
                        if (flag) {
                            questionResult = '0'
                            // item['imgPath'] = this.img2
                        } else {
                            questionResult = '1'
                            // item['imgPath'] = this.img
                        }
                        item['questionResult'] = questionResult
                        checkbox['questionResult'] = questionResult
                        this.questionBase.push(checkbox)
                    }
                })
                this.$http.post(Api.paper+'/saveErrorQuestionResult', this.questionBase).then(res => {
                    if (res.data.status === 200) {
                        this.formLoading = false
                        this.submitBtn = false
                        this.saveStatus = true
                    } else {
                        this.formLoading = false
                        this.submitBtn = false
                        this.$Message.error(res.data.msg)
                    }
                }).catch(item => {
                    this.formLoading = false
                    this.submitBtn = false
                })
            },
            query(){
                this.listLoading = true;
                let data = {
                    page: this.pagedata.pageNumber,
                    rows: this.pagedata.pageSize,
                };
                data = Object.assign(data,JSON.parse(JSON.stringify(this.searchTable)));
                this.$http.get(Api.paper+'/getErrorQuestionPageList',{
                    params:data,
                    paramsSerializer: params => {
                        return qs.stringify(params, { indices: false })
                    }
                }).then((res) => {
                    this.tableData = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.listLoading = false;
                }).catch( e => {
                    this.$Message.error('请求失败');
                });
            },
            search() {
                this.pagedata.pageNumber = 1
                this.query()
            },
            reset(val) {
                this.pagedata.pageNumber = 1
                this.pagedata.pageSize = 10
                this.searchTable = {}
                this.query()
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },

            remove(id){
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>确定移出吗</p>',
                    okText: '确认',
                    onOk: () => {
                        this.listLoading = true
                        this.$http.delete(Api.paper+'/deleteErrorQuestionById/'+id).then(res => {
                            this.listLoading = false
                            if (res.data.status === 200) {
                                if (res.data.data) {
                                    this.$Message.success('移出成功')
                                    this.query()
                                } else {
                                    this.listLoading = true
                                    this.$Message.error('移出失败')
                                }
                            } else {
                                this.$Message.error(res.msg)
                            }
                        })
                    },
                    cancelText: '取消'
                });
            },

        }
    }
</script>

<style lang='css' scoped>
    @import '../../../../index.css';
</style>
